<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />




  


  <link rel="alternate" href="/atom.xml" title="yampery" type="application/atom+xml" />






<meta name="description" content="本文以redis为数据结构基础，配合Spring管理机制，使用java实现了一个轻量级、可配置的消息队列。适合的项目特点：  Spring框架管理对象 有消息需求，但不想维护mq中间件 有使用redis 对消息持久化并没有很苛刻的要求  需要使用rabbitmq实现延迟消息请参考这里  设计方案设计主要包含以下几点：  将整个Redis当做消息池，以kv形式存储消息 使用ZSET做优先队列，按照s">
<meta property="og:type" content="article">
<meta property="og:title" content="基于Redis的消息队列">
<meta property="og:url" content="https://yampery.gitee.io/2019/02/25/redis/rdsmq/index.html">
<meta property="og:site_name" content="yampery">
<meta property="og:description" content="本文以redis为数据结构基础，配合Spring管理机制，使用java实现了一个轻量级、可配置的消息队列。适合的项目特点：  Spring框架管理对象 有消息需求，但不想维护mq中间件 有使用redis 对消息持久化并没有很苛刻的要求  需要使用rabbitmq实现延迟消息请参考这里  设计方案设计主要包含以下几点：  将整个Redis当做消息池，以kv形式存储消息 使用ZSET做优先队列，按照s">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20180209131159151?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2l6YXJkX3Jw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:updated_time" content="2019-01-30T01:41:05.097Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于Redis的消息队列">
<meta name="twitter:description" content="本文以redis为数据结构基础，配合Spring管理机制，使用java实现了一个轻量级、可配置的消息队列。适合的项目特点：  Spring框架管理对象 有消息需求，但不想维护mq中间件 有使用redis 对消息持久化并没有很苛刻的要求  需要使用rabbitmq实现延迟消息请参考这里  设计方案设计主要包含以下几点：  将整个Redis当做消息池，以kv形式存储消息 使用ZSET做优先队列，按照s">
<meta name="twitter:image" content="http://img.blog.csdn.net/20180209131159151?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2l6YXJkX3Jw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://yampery.gitee.io/2019/02/25/redis/rdsmq/"/>





  <title>基于Redis的消息队列 | yampery</title>
  








  <link href='//fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yampery</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天尽头，回眸望红尘</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yampery.gitee.io/2019/02/25/redis/rdsmq/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yampery">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yampery">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">基于Redis的消息队列</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-25T11:05:38+08:00">
                2019-02-25
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2019/02/25/redis/rdsmq/" class="leancloud_visitors" data-flag-title="基于Redis的消息队列">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.3k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文以redis为数据结构基础，配合Spring管理机制，使用java实现了一个轻量级、可配置的消息队列。适合的项目特点：</p>
<ul>
<li><strong>Spring框架管理对象</strong></li>
<li><strong>有消息需求，但不想维护mq中间件</strong></li>
<li><strong>有使用redis</strong></li>
<li><strong>对消息持久化并没有很苛刻的要求</strong></li>
</ul>
<p><em><a href="http://blog.csdn.net/wizard_rp/article/details/79310206" target="_blank" rel="noopener">需要使用rabbitmq实现延迟消息请参考这里</a></em></p>
<hr>
<h1 id="设计方案"><a href="#设计方案" class="headerlink" title="设计方案"></a>设计方案</h1><p><strong>设计主要包含以下几点：</strong></p>
<ul>
<li>将整个Redis当做消息池，以kv形式存储消息</li>
<li>使用ZSET做优先队列，按照score维持优先级</li>
<li>使用LIST结构，以先进先出的方式消费</li>
<li>zset和list存储消息地址（对应消息池的每个key）</li>
<li>自定义路由对象，存储zset和list名称，以点对点的方式将消息从zset路由到正确的list</li>
<li>使用定时器维持路由</li>
<li>根据TTL规则实现消息延迟</li>
</ul>
<p> <img src="http://img.blog.csdn.net/20180209131159151?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2l6YXJkX3Jw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="基于Redis有消息队列设计方案"></p>
<h1 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h1><h2 id="技术说明"><a href="#技术说明" class="headerlink" title="技术说明"></a>技术说明</h2><blockquote>
<p>示例使用Springboot，gradle，redis，jdk8。</p>
</blockquote>
<h2 id="核心代码"><a href="#核心代码" class="headerlink" title="核心代码"></a>核心代码</h2><blockquote>
<p>核心代码主要包含消息对象Message，路由器Route和消息队列RedisMQ。</p>
</blockquote>
<h3 id="Message对象"><a href="#Message对象" class="headerlink" title="Message对象"></a>Message对象</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.msmq;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> Message</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;封装消息元数据&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/11/2 15:50</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Message</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息主题</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String topic;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息延迟</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> delay;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息优先级</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> priority;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息存活时间</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> ttl;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息体，对应业务内容</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String body;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建时间，如果只有优先级没有延迟，可以设置创建时间为0</span></span><br><span class="line"><span class="comment">     * 用来消除时间的影响</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> createTime;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息状态（延迟-0；待发送-1；已发送-2；发送失败-3）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> status;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * getset略...</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Route-消息路由器"><a href="#Route-消息路由器" class="headerlink" title="Route(消息路由器)"></a>Route(消息路由器)</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.msmq;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> Route</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;消息路由器，主要控制将消息从指定的队列路由到待消费的list&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 通过这种方式实现自定义延迟以及优先级发送&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/11/3 14:33</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Route</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存放消息的队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String queue;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 待消费的列表</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String list;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Route</span><span class="params">(String queue, String list)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.queue = queue;</span><br><span class="line">        <span class="keyword">this</span>.list = list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * getset略...</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="RedisMq-消息队列"><a href="#RedisMq-消息队列" class="headerlink" title="RedisMq(消息队列)"></a>RedisMq(消息队列)</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.msmq;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> git.yampery.utils.JedisUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scheduling.annotation.Scheduled;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> RedisMQ</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;基于redis的消息队列&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;将整个redis作为消息池存储消息体，以ZSET为消息队列，LIST作为待消费列表&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 用Spring定时器作为监听器，每次监听ZSET中指定数量的消息&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 根据SCORE确定是否达到发送要求，如果达到，利用消息路由&#123;<span class="doctag">@link</span> Route&#125;将消息路由到待消费list&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/11/2 15:49</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisMQ</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息池前缀，以此前缀加上传递的消息id作为key，以消息&#123;<span class="doctag">@link</span> Message&#125;</span></span><br><span class="line"><span class="comment">     * 的消息体body作为值存储</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String MSG_POOL = <span class="string">"Message:Pool:"</span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 默认监听数量，对应监听zset队列前多少个元素</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAUT_MONITOR = <span class="number">10</span>;</span><br><span class="line">    <span class="meta">@Resource</span> <span class="keyword">private</span> JedisUtils jedisUtils;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 每次监听queue中元素的数量，可配置</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> monitorCount = DEFAUT_MONITOR;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息路由</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Route&gt; routes;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存入消息池</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> message</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addMsgPool</span><span class="params">(Message message)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != message) &#123;</span><br><span class="line">            <span class="keyword">return</span> jedisUtils.setex(MSG_POOL + message.getId(), message.getBody(), message.getTtl());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 从消息池中删除消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deMsgPool</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> jedisUtils.del(MSG_POOL + id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 像队列中添加消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> score 优先级</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> val</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 返回消息id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">enMessage</span><span class="params">(String key, <span class="keyword">long</span> score, String val)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (jedisUtils.zadd(key, score, val)) &#123;</span><br><span class="line">            <span class="keyword">return</span> val;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 从队列删除消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deMessage</span><span class="params">(String key, String id)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> jedisUtils.zdel(key, id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消费</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;String&gt; <span class="title">consume</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> count = jedisUtils.countList(key);</span><br><span class="line">        <span class="keyword">if</span> (<span class="number">0</span> &lt; count) &#123;</span><br><span class="line">            <span class="comment">// 可根据需求做限制</span></span><br><span class="line">            List&lt;String&gt; ids = jedisUtils.rangeList(key, <span class="number">0</span>, count - <span class="number">1</span>);</span><br><span class="line">            <span class="keyword">if</span> (ids != <span class="keyword">null</span>) &#123;</span><br><span class="line">                List&lt;String&gt; result = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">                ids.forEach(l -&gt; result.add(jedisUtils.get(MSG_POOL + l, <span class="string">""</span>)));</span><br><span class="line">                jedisUtils.removeListValue(key, ids);</span><br><span class="line">                <span class="keyword">return</span> result;</span><br><span class="line">            &#125; <span class="comment">/// if end~</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 消息队列监听器&lt;br&gt;</span></span><br><span class="line"><span class="comment">     * 监听所有路由器，将消息队列中的消息路由到待消费列表</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Scheduled</span>(cron=<span class="string">"*/5 * * * * *"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">monitor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取消息路由</span></span><br><span class="line">        <span class="keyword">int</span> route_size;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> == routes || <span class="number">1</span> &gt; (route_size = routes.size())) <span class="keyword">return</span>;</span><br><span class="line">        String queue, list;</span><br><span class="line">        Set&lt;String&gt; set;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; route_size; i++) &#123;</span><br><span class="line">            queue = routes.get(i).getQueue();</span><br><span class="line">            list = routes.get(i).getList();</span><br><span class="line">            set = jedisUtils.getSoredSetByRange(queue, <span class="number">0</span>, monitorCount, <span class="keyword">true</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> != set) &#123;</span><br><span class="line">                <span class="keyword">long</span> current = System.currentTimeMillis();</span><br><span class="line">                <span class="keyword">long</span> score;</span><br><span class="line">                <span class="keyword">for</span> (String id : set) &#123;</span><br><span class="line">                     score = jedisUtils.getScore(queue, id).longValue();</span><br><span class="line">                    <span class="keyword">if</span> (current &gt;= score) &#123;</span><br><span class="line">                        <span class="comment">// 添加到list</span></span><br><span class="line">                        <span class="keyword">if</span> (jedisUtils.insertList(list, id)) &#123;</span><br><span class="line">                            <span class="comment">// 删除queue中的元素</span></span><br><span class="line">                            deMessage(queue, id);</span><br><span class="line">                        &#125; <span class="comment">/// if end~</span></span><br><span class="line">                    &#125; <span class="comment">/// if end~</span></span><br><span class="line">                &#125; <span class="comment">/// for end~</span></span><br><span class="line">            &#125; <span class="comment">/// if end~</span></span><br><span class="line">        &#125; <span class="comment">/// for end~</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMonitorCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> monitorCount;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMonitorCount</span><span class="params">(<span class="keyword">int</span> monitorCount)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.monitorCount = monitorCount;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Route&gt; <span class="title">getRoutes</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> routes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRoutes</span><span class="params">(List&lt;Route&gt; routes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.routes = routes;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="RedisMq消息队列配置："><a href="#RedisMq消息队列配置：" class="headerlink" title="RedisMq消息队列配置："></a>RedisMq消息队列配置：</h3><ul>
<li>mq.properties文件</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"># 队列的监听数量</span><br><span class="line">mq.monitor.count                 =30</span><br><span class="line"># 队列一</span><br><span class="line">mq.queue.first                  =queue:1</span><br><span class="line"># 队列二</span><br><span class="line">mq.queue.second                 =queue:2</span><br><span class="line"># 消费列表一</span><br><span class="line">mq.consumer.first               =list:1</span><br><span class="line"># 消费列表二</span><br><span class="line">mq.consumer.second              =list:2</span><br></pre></td></tr></table></figure>
<ul>
<li>MqConfig.java文件</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> git.yampery.msmq.RedisMQ;</span><br><span class="line"><span class="keyword">import</span> git.yampery.msmq.Route;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Value;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Primary;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> MqConfig</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;消息队列配置&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/2/9 14:26</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 根据不同的架构可选择使用XML配置</span></span><br><span class="line"><span class="comment"> * ---------------------------------------------------</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment">    &lt;bean id="redisMQ" class="git.yampery.msmq.RedisMQ"&gt;</span></span><br><span class="line"><span class="comment">        &lt;property name="monitorCount" value="15"/&gt;</span></span><br><span class="line"><span class="comment">        &lt;property name="routes"&gt;</span></span><br><span class="line"><span class="comment">            &lt;list&gt;</span></span><br><span class="line"><span class="comment">                &lt;bean class="git.yampery.msmq.Route"&gt;</span></span><br><span class="line"><span class="comment">                    &lt;property name="queue" value="$&#123;mq.queue.first&#125;"/&gt;</span></span><br><span class="line"><span class="comment">                    &lt;property name="list" value="$&#123;mq.consumer.first&#125;"/&gt;</span></span><br><span class="line"><span class="comment">                &lt;/bean&gt;</span></span><br><span class="line"><span class="comment">                &lt;bean class="git.yampery.msmq.Route"&gt;</span></span><br><span class="line"><span class="comment">                    &lt;property name="queue" value="$&#123;mq.queue.second&#125;"/&gt;</span></span><br><span class="line"><span class="comment">                    &lt;property name="list" value="$&#123;mq.consumer.second&#125;"/&gt;</span></span><br><span class="line"><span class="comment">                &lt;/bean&gt;</span></span><br><span class="line"><span class="comment">            &lt;/list&gt;</span></span><br><span class="line"><span class="comment">        &lt;/property&gt;</span></span><br><span class="line"><span class="comment">    &lt;/bean&gt;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * ----------------------------------------------------</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MqConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"redisMQ"</span>)</span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RedisMQ <span class="title">getRedisMq</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        RedisMQ redisMQ = <span class="keyword">new</span> RedisMQ();</span><br><span class="line">        <span class="comment">// 配置监听队列元素数量</span></span><br><span class="line">        redisMQ.setMonitorCount(monitorCount);</span><br><span class="line">        <span class="comment">// 配置路由表</span></span><br><span class="line">        redisMQ.setRoutes(routeList());</span><br><span class="line">        <span class="keyword">return</span> redisMQ;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 返回路由表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Route&gt; <span class="title">routeList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;Route&gt; routeList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        Route routeFirst = <span class="keyword">new</span> Route(queueFirst, listFirst);</span><br><span class="line">        Route routeSecond = <span class="keyword">new</span> Route(queueSecond, listSecond);</span><br><span class="line">        routeList.add(routeFirst);</span><br><span class="line">        routeList.add(routeSecond);</span><br><span class="line">        <span class="keyword">return</span> routeList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.monitor.count&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> monitorCount;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.queue.first&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String queueFirst;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.queue.second&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String queueSecond;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.consumer.first&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String listFirst;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.consumer.second&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String listSecond;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>如果使用的是xml配置</strong>　请参考：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"redisMQ"</span> <span class="attr">class</span>=<span class="string">"git.yampery.msmq.RedisMQ"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"monitorCount"</span> <span class="attr">value</span>=<span class="string">"15"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"routes"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"git.yampery.msmq.Route"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"queue"</span> <span class="attr">value</span>=<span class="string">"$&#123;mq.queue.first&#125;"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"list"</span> <span class="attr">value</span>=<span class="string">"$&#123;mq.consumer.first&#125;"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"git.yampery.msmq.Route"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"queue"</span> <span class="attr">value</span>=<span class="string">"$&#123;mq.queue.second&#125;"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"list"</span> <span class="attr">value</span>=<span class="string">"$&#123;mq.consumer.second&#125;"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="消费者"><a href="#消费者" class="headerlink" title="消费者"></a>消费者</h3><blockquote>
<p>并没有内置消费者监听器来实现，可以直接使用定时器实现</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.task;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSONObject;</span><br><span class="line"><span class="keyword">import</span> git.yampery.msmq.RedisMQ;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scheduling.annotation.Scheduled;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.StringUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> MsgTask</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;发送消息&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/2/9 18:04</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MsgTask</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span> <span class="keyword">private</span> RedisMQ redisMQ;</span><br><span class="line">    <span class="comment">// @Value("$&#123;mq.list.first&#125;") private String MQ_LIST_FIRST;</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Scheduled</span>(cron=<span class="string">"*/5 * * * * *"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendMsg</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 消费</span></span><br><span class="line">        List&lt;String&gt; msgs = redisMQ.consume(redisMQ.getRoutes().get(<span class="number">0</span>).getList());</span><br><span class="line">        <span class="keyword">int</span> len;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != msgs &amp;&amp; <span class="number">0</span> &lt; (len = msgs.size())) &#123;</span><br><span class="line">            <span class="comment">// 将每一条消息转为JSONObject</span></span><br><span class="line">            JSONObject jObj;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">                <span class="keyword">if</span> (!StringUtils.isEmpty(msgs.get(i))) &#123;</span><br><span class="line">                    jObj = JSONObject.parseObject(msgs.get(i));</span><br><span class="line">                    <span class="comment">// 取出消息</span></span><br><span class="line">                    System.out.println(jObj.toJSONString());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h1><blockquote>
<p>测试设置20秒延迟，发布消息到queue:1，在list:1消费。
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> git.yampery.mq;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSONObject;</span><br><span class="line"><span class="keyword">import</span> git.yampery.msmq.Message;</span><br><span class="line"><span class="keyword">import</span> git.yampery.msmq.RedisMQ;</span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"><span class="keyword">import</span> org.junit.runner.RunWith;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Value;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"><span class="keyword">import</span> org.springframework.test.context.junit4.SpringRunner;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.util.UUID;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@decription</span> TestMQ</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;测试&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Yampery</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018/2/9 18:43</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RunWith</span>(SpringRunner.class)</span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestMQ</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> RedisMQ redisMQ;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mq.queue.first&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String MQ_QUEUE_FIRST;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testMq</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        JSONObject jObj = <span class="keyword">new</span> JSONObject();</span><br><span class="line">        jObj.put(<span class="string">"msg"</span>, <span class="string">"这是一条短信"</span>);</span><br><span class="line"></span><br><span class="line">        String seqId = UUID.randomUUID().toString();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将有效信息放入消息队列和消息池中</span></span><br><span class="line">        Message message = <span class="keyword">new</span> Message();</span><br><span class="line">        message.setBody(jObj.toJSONString());</span><br><span class="line">        <span class="comment">// 可以添加延迟配置</span></span><br><span class="line">        message.setDelay(<span class="number">20</span>);</span><br><span class="line">        message.setTopic(<span class="string">"SMS"</span>);</span><br><span class="line">        message.setCreateTime(System.currentTimeMillis());</span><br><span class="line">        message.setId(seqId);</span><br><span class="line">        <span class="comment">// 设置消息池ttl，防止长期占用</span></span><br><span class="line">        message.setTtl(<span class="number">20</span> * <span class="number">60</span>);</span><br><span class="line">        message.setStatus(<span class="number">0</span>);</span><br><span class="line">        message.setPriority(<span class="number">0</span>);</span><br><span class="line">        redisMQ.addMsgPool(message);</span><br><span class="line">        redisMQ.enMessage(MQ_QUEUE_FIRST,</span><br><span class="line">                message.getCreateTime() + message.getDelay() + message.getPriority(), message.getId());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>文章利用redis已有的数据存储结构，实现了轻量级的消息队列，并未真正实现消息持久化。示例是针对点对点的消息路由方式，当然，也可以扩展成广播和主题的方式，不过，这样就得不偿失了，如果需求比较复杂，可靠性要求较高，反而不如直接维护rabbitmq之类的消息队列。 
<em><a href="http://blog.csdn.net/wizard_rp/article/details/79310206" target="_blank" rel="noopener">需要使用rabbitmq实现延迟消息请参考这里</a></em></p>
<h1 id="源码连接"><a href="#源码连接" class="headerlink" title="源码连接"></a>源码连接</h1><blockquote>
<p>文章并未贴出所有代码，gradle构建、jedisUtils以及一些配置等可以参考源码，源码只需要设置自己的redis配置即可。
<a href="https://github.com/Yampery/rdsmq.git" target="_blank" rel="noopener">https://github.com/Yampery/rdsmq.git</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/25/ykt_test_binding/" rel="next" title="性能测试">
                <i class="fa fa-chevron-left"></i> 性能测试
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">yampery</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yampery" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1yampery@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#设计方案"><span class="nav-number">1.</span> <span class="nav-text">设计方案</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#代码实现"><span class="nav-number">2.</span> <span class="nav-text">代码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#技术说明"><span class="nav-number">2.1.</span> <span class="nav-text">技术说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核心代码"><span class="nav-number">2.2.</span> <span class="nav-text">核心代码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Message对象"><span class="nav-number">2.2.1.</span> <span class="nav-text">Message对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Route-消息路由器"><span class="nav-number">2.2.2.</span> <span class="nav-text">Route(消息路由器)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RedisMq-消息队列"><span class="nav-number">2.2.3.</span> <span class="nav-text">RedisMq(消息队列)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RedisMq消息队列配置："><span class="nav-number">2.2.4.</span> <span class="nav-text">RedisMq消息队列配置：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#消费者"><span class="nav-number">2.2.5.</span> <span class="nav-text">消费者</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#测试"><span class="nav-number">3.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#源码连接"><span class="nav-number">5.</span> <span class="nav-text">源码连接</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yampery</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">NexT.Mist</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("35rGUMRzp5wPN2jmmIUWeBNh-gzGzoHsz", "fmF6mJDmgl0FkqBKX8I2HiGF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
